<template>
    <div class="container autoGrow flex-row">
        <div class="choose-type flex-column">
            <div class="layui-card flex-column choose-account-card">
                <div class="layui-card-header">选择客服账号</div>
                <div class="layui-card-body choose-account-list">
                    <el-select v-model="accountCheckedId">
                        <el-option class="option-account-item" v-for="(item) in accounts" :key="item.id" :value="item.id" :label="item.name">
                            <friend
                                :avatar="item.avatar"
                                :name="item.name"
                                :wxid="item.wxid"
                                :gender="item.gender"
                                class="account-item-friend"
                            />
                        </el-option>
                    </el-select>

                </div>
            </div>

            <div class="layui-card flex-column account-card">
                <div class="layui-card-header account-card-title">
                    <div>
                        选择{{type===1?'群':'客服账号'}}
                        <el-tooltip v-if="type===1" class="item" effect="dark" content="只显示人数在99人以下的群" placement="top">
                        <i class="el-icon-warning-outline"></i></el-tooltip>
                    </div>
                </div>
               
                <div class="layui-card-body account-list">
                    <label class="flex-row account-item" v-for="(item) in groups" :key="item.id">
                        <input :checked="groupChecked.includes(item.id)" type="checkbox" name="" @change="groupChange(item)">
                        <el-tooltip :content="item.groupname" placement="top">
                        <user-wrapper
                            :avatar="item.avatar"
                            :title="item.groupname"
                            :info="accountsWxidMap[item.wxaccount].name"
                            class="account-item-group" />
                        </el-tooltip>
                    </label>
                </div>
            </div>
        </div>
        <div class="choose-account flex-column">
            <div class="layui-card name-card">
                <div class="layui-card-header">活动名称</div>
                <div class="layui-card-body">
                    <div class="layui-form">
                        <input type="text" v-model="taskname" name="title" required  lay-verify="required" placeholder="请输入名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-card name-card">
                <div class="layui-card-header">邀请人数条件</div>
                <div class="layui-card-body">
                    <div class="layui-form">
                        <input type="text" v-model="invitelimit" name="title" required  lay-verify="required" placeholder="请输入名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-card name-card">
                <div class="layui-card-header">达成条件消息</div>
                <div class="layui-card-body">
                    <div class="layui-card-body replies">
                        <messageButtonGroup 
                            v-if="accountCheckedId"
                            :csid="uistate.adminid"
                            :wxid="accountMap[accountCheckedId].wxid"
                            @create="createReply"
                            :types="['text','image','video','link','file','card','document','forward']"
                        /> 
                        <div class="quick-plane">
                            <div class="quick-item" v-for="(reply, index) in replymsg" :key="index">
                            <div class="quick-item-createtime" style="text-align:right">
                                <i @click.stop="replymsg.splice(index,1)" class="el-icon-close quick-item-close"></i>
                            </div>
                            <messageCard :message="reply" />
                            </div>
                        </div> 
                    </div>
                   
                </div>
            </div>
            <div class="layui-card name-card">
                <div class="layui-card-header">未达成条件消息</div>
                <div class="layui-card-body">
                    <div class="layui-card-body replies">
                        <messageButtonGroup 
                            v-if="accountCheckedId"
                            :csid="uistate.adminid"
                            :wxid="accountMap[accountCheckedId].wxid"
                            @create="createUnqualReply"
                            :types="['text','image','video','link','file','card','document','forward']"
                        /> 
                        <div class="quick-plane">
                            <div class="quick-item" v-for="(reply, index) in unqualifedmsg" :key="index">
                            <div class="quick-item-createtime" style="text-align:right">
                                <i @click.stop="unqualifedmsg.splice(index,1)" class="el-icon-close quick-item-close"></i>
                            </div>
                            <messageCard :message="reply" />
                            </div>
                        </div> 
                    </div>
                </div>
            </div>
            <el-row :gutter="10">
                <el-col :span="24" v-if="!tempRecord"><button @click="sendSave" type="button" class="layui-btn layui-btn-fluid col-md-6">生成活动</button></el-col>
                <template v-else>
                    <el-col :span="12"><button @click="sendSave" type="button" class="layui-btn layui-btn-fluid col-md-6">保存编辑</button></el-col>
                    <el-col :span="12"><button @click="cancelEdit" type="button" class="layui-btn layui-btn-fluid">取消</button></el-col>
                </template>
                
            </el-row>
            
        </div>
        <div ref="list" class="detail-container autoGrow flex-column infinite-list" infinite-scroll-immediate="false" v-infinite-scroll="load" v-loading="recordLoading && pageNo===0">
            <fieldset><legend><span name="fieldset">活动列表</span></legend></fieldset>
            <blockquote class="layui-card layui-elem-quote detail-item" v-for="(record) in records" :key="record.id">
                <div class="layui-card-body">
                    <div class="flex-row detail-content">
                        <div>
                        <span>{{record.taskname}}</span>
                        <span class="fontGrey">（{{ formatTime(record.createtime) }} 配置）</span>
                        </div>
                        <div>
                            <el-button  size="small" slot="reference" type="danger" @click="delRecord(record)">删除<i class="el-icon-delete el-icon--right"></i></el-button>
                            <el-button  size="small" slot="reference" type="primary" @click="editRecord(record)">编辑<i class="el-icon-edit el-icon--right"></i></el-button>
                        </div>
                    </div>
                    <div class="layui-card detail-setting">
                        <div class="layui-card-header">活动群</div>
                        <div class="layui-card-body">
                            <div class="detail-setting-list">
                                <label class="flex-row account-item detail-setting-item" v-for="(groupno) in record.taskgroup" :key="groupno">
                                    <el-tooltip :content="groupsMapByNo[groupno].groupname" placement="top" v-if="groupsMapByNo[groupno]">
                                        <user-wrapper
                                    :avatar="groupsMapByNo[groupno].avatar"
                                    :title="groupsMapByNo[groupno].groupname"
                                    :info="'共'+groupsMapByNo[groupno].personnum+'人 '"
                                    class="account-item-friend" />
                                    </el-tooltip>
                                </label>

                            </div>
                            
                        </div>
                    </div>
                </div>
            </blockquote>
        </div>
        
    </div>
</template>
<script>
import friend from '@/components/friend'
import group from '@/components/group'
import userWrapper from '@/components/user-wrapper';
import uploadPictureCard from "@/components/upload-picture-card";
import { mapState } from 'vuex';
import messageButtonGroup from '@/components/message-button-group'
import messageCard from '@/components/message-card'

export default {
    data(){
        return {
            type:1,
            recordLoading:false,
            accountChecked:[],
            accountCheckedId:'',
            replymsg:[],
            unqualifedmsg:[],
            accountDialogChecked:[],
            groupDialogChecked:[],
            groupsMap:{},


            taskname:'',
            invitelimit:0,

            groupOwner:true,

            accountServiceChecked:[],
            groupChecked:[],

            records:[],
            tempRecord:null,

            groupDialogAccount:{},
            qrcodeBase:'',

            pageNo:0,
            pageSize:10

        }
    },

    components:{
        friend,group,userWrapper,uploadPictureCard,messageButtonGroup,messageCard
    },
    computed:{
        ...mapState(['accountMap','accountListMap','uistate']),
        accountsWxidMap(){
            const {adminid} = this.uistate
            if( adminid ===-1 || !this.accountListMap[adminid] )return []
            let map = {}
            this.accountListMap[adminid].forEach(id=>{
                const item = this.accountMap[id]
                map[item.wxid] = {
                    id:item.id,
                    csid:item.csid,
                    name:item.nick,
                    avatar:item.avatar,
                    wxid:item.wxid,
                    gender:item.gender,
                    friendcount:item.friendcount
                }
            })
            return map

        },
        accounts(){
            const {adminid} = this.uistate 
            if( adminid ===-1 || !this.accountListMap[adminid] )return []
            const accounts = this.accountListMap[adminid].map(id=>{
                const item = this.accountMap[id]
                return {
                    id:item.id,
                    csid:item.csid,
                    name:item.nick,
                    avatar:item.avatar,
                    wxid:item.wxid,
                    gender:item.gender,
                    friendcount:item.friendcount,
                    wxaccount:item.wxaccount
                }
            })
            return accounts
        },
        groups(){
            const accountChecked = this.accountChecked
            const groups = accountChecked.map(id=>this.groupsMap[id]).filter(item=>item)
            const _groups = [].concat.apply([], groups);
            const isonwer = this.groupOwner
            return _groups.filter(group=>group.personnum<=150 && ( group.isfirst=== (isonwer?1:2) ))
        },
        groupsMapByNo(){
            let _groups = {}
            this.groups.forEach(g=>{
                _groups[g.groupno] = g
            })
            return _groups

        },
        dialogGroups(){
            const account = this.groupDialogAccount
            if(!account.id)return;
            const { id } = account
            return (this.groupsMap[id]||[]).filter(group=>group.personnum<=200)
        }
    },
    mounted(){
        // this.getRecords()
    },
    watch:{
        type(type,oldType){
            if(type!==oldType){
                this.pageNo = 0
                this.records = []
                this.getRecords()
            }
        },
        accountCheckedId(val,oldVal){
            if(val){
                this.accountChecked = [val]
                this.getGroupsByAccount()
                this.reset()
                this.refresh()
            }
            
        }
    },
    methods:{
        reset(){
            this.taskname = ''
            this.invitelimit = 0
            this.groupChecked = []
            this.replymsg = []
            this.unqualifedmsg = []
            this.tempRecord = null

        },
        refresh(){
            this.pageNo = 0
            this.records = []
            this.getRecords()
        },
        /** 添加账号弹窗 */
        editRecord(record){
            this.tempRecord = record
            this.taskname = record.taskname 
            this.invitelimit = record.invitelimit  
            try {
                this.replymsg = JSON.parse(record.replymsg)   
                this.unqualifedmsg = JSON.parse(record.unqualifedmsg)
            } catch (error) {
                console.log(error)
            }
            let _groupsmap = {}
            this.groups.forEach(g=>{ _groupsmap[g.groupno] = g })
            this.groupChecked =  record.taskgroup.map(groupno=>{
                return _groupsmap[groupno].id
            })
            console.log(record.taskgroup)
            
            console.log(_groupsmap)

               
        },
        cancelEdit(){
            this.reset()
        },
         
        /** 添加账号弹窗 */
        /** 添加群弹窗 */
        
        /** 添加群弹窗 */
        getGroupsByAccount(){
            const { adminid } = this.uistate
            this.accountChecked.forEach(id=>{
                if(this.groupsMap[id]&&this.groupsMap[id].length)return;
                const account = this.accountMap[id]
                this.getGroup(adminid,account.wxid,account.id)
            })
            // Object.keys(this.groupsMap).forEach(key=>{
            //     if(!this.accountChecked.includes(key)){
            //         this.$set(this.groupsMap, key, [])
            //     }
            // })

        },
        getGroup(csid,wxaccount,id){
            this.$api.group.list({
                csid,
                wxaccount
            }).then(data=>{
                this.$set(this.groupsMap, id, data)
            }).catch(e=>this.$msg(e))
        },

        accountServiceChange(item){
            if(this.accountServiceChecked.includes(item.id)){
                this.accountServiceChecked = this.accountServiceChecked.filter(id=>id!=item.id)
            }else{
                this.accountServiceChecked.push(item.id)
            }
        },

        groupChange(item){
            if(this.groupChecked.includes(item.id)){
                this.groupChecked = this.groupChecked.filter(id=>id!=item.id)
            }else{
                this.groupChecked.push(item.id)
            }
        },

        load(){
           this.getRecords()
        },
        getRecords(){

            const accounts = this.accountMap
            const account = accounts[this.accountCheckedId]
            if(!account)return 

            
            const params = {
                wxaccount:account.wxid,
                pageNo:this.pageNo+1,
                pageSize:this.pageSize
            }
            if(this.recordLoading)return
            this.recordLoading = true
            this.$api.award.getRecords(params)
                .then(data=>{
                    if(this.pageNo){
                        return this.$message({message:'没有更多了'})
                    }
                    this.pageNo = params.pageNo
                    try {
                        data = data.map(item=>{
                            item.taskgroup = (item.taskgroup||[]).split(',')
                            return item 
                        })
                         
                    } catch (error) {
                        console.log(error)
                    }
                    console.log(data)
                    if(this.pageNo === 1){
                        this.records = data
                    }else{
                        this.records = this.records.concat(data)
                    }
                    this.recordLoading = false

                })
                .catch(e=>{
                    this.recordLoading = false
                    this.$msg(e)

                })
        },
        sendSave(){
            
            const taskname = this.taskname.trim()
            const invitelimit = +this.invitelimit 
            const accounts = this.accountMap
            const _accounts = accounts[this.accountCheckedId]

            if(!_accounts.wxid)return this.$msg('请选择客服帐号')
            if(!taskname)return this.$msg('请填写活动名称')
            if(!invitelimit)return this.$msg('请填写邀请条件')
            if(!this.replymsg.length)return this.$msg('请填写达成回复')
            if(!this.unqualifedmsg.length)return this.$msg('请填写未达成回复')

            
            let _groups = []
            this.groups.forEach(item=>{
                if(this.groupChecked.includes(item.id))_groups.push(item)
            })

            let itemids =  _groups.map(group=>{
                    return group.groupno
                }).join(',')
            if(!itemids.length)return this.$msg('请选择群') 
            const params = {
                wxaccount:_accounts.wxid,
                taskname,
                invitelimit,
                replymsg:JSON.stringify(this.replymsg),
                unqualifedmsg:JSON.stringify(this.unqualifedmsg),
                taskgroup:itemids
            }
            if(this.tempRecord && this.tempRecord.id){
                params.id = this.tempRecord.id
            }
            this.$api.award.saveGroupAward(params)
                .then(data=>{
                    this.$msg('保存成功')
                    this.reset()
                    this.refresh()
                })
                .catch(this.$msg)

        },
         
        delRecord(record){
            const { id } = record

            const params = {
                id
                
            }
            this.$api.award.deleteRecord(params)
                .then(data=>{
                    this.refresh()
                    this.$msg('删除成功')
                })
                .catch(this.$msg)

        },
        
        createReply(reply){
            this.replymsg.unshift(reply)
        },
        createUnqualReply(reply){
            this.unqualifedmsg.unshift(reply)
        }

    }
}
</script>
<style scoped lang="scss">
.container{
    border-top: 1px solid #ccc;
    height: 100%;
    overflow: hidden;
}
.option-account-item{
    padding: 10px;
    height: auto;
}
.choose-type{
    width: 260px;
    overflow: auto;
    flex-shrink: 0;
    border-right: 1px solid #ccc;
    background: #e2e2e2;
    padding: 15px;
    box-sizing: border-box;
}
.choose-account{
    width: 260px;
    height: 100%;
    overflow: auto;
    flex-shrink: 0;
    border-right: 1px solid #ccc;
    background: #f1f1f1;
    padding: 15px;
    box-sizing: border-box;
}
.account-card{
    height: 100%;
}
.account-card-title{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}
.choose-type{
    height:100%;
}
.choose-card{

}
.bgurl-select{
    flex-shrink: 0;
    margin-right: 10px;
}
.edit-bgurl{
    position: absolute;
    top: 0;
    left: 0;

    width: 100%;
    height:100%;
    z-index: 1;
    opacity: 0;
}
.choose-account-card{
    // height:100%;
    /* margin-bottom: 10px; */
}
.choose-account-list{
    height:100%;
    overflow: auto;
}
.account-list{
    height:100%;
    overflow: auto
}
.account-item{
    align-items: center;
    margin-bottom: 10px;
}
.account-item:last-child{
    margin-bottom: 0
}
.account-item-friend,
.account-item-group{
    margin-left: 5px;
    overflow: hidden;
}
.detail-container{
    background-color: #f2f2f2;
    padding:15px;
    box-sizing: border-box;
    height: 100%;
    overflow: auto;
}
.detail-container fieldset {
    border: none;
    padding: 0;
    border-top: 1px solid #ddd;
    margin-bottom: 10px;
}
.detail-container fieldset legend {
    margin-left: 20px;
    padding: 0 10px;
    font-size: 22px;
    font-weight: 300;
}
.detail-item{
    background: #fafafa;
    padding:0;
}
.detail-setting{
    margin-top: 10px;
}
.detail-content{
    align-items: center;
    justify-content: space-between;
}
.detail-setting-list{
    display: grid;
    grid-template-columns: 25% 25% 25% 25%;
    grid-row-gap: 5px;
    grid-column-gap: 5px;
}
.detail-setting-item{
    margin-bottom: 0
}
.detail-setting-ctrl{
    margin-top:10px;
    text-align: right;
}
.group-dialog{
    padding: 0;

}
.group-dialog-left{
    background: #eee;
    box-shadow: -10px 0px 10px -10px #999 inset;
    width: 200px;
    overflow: auto
}
.group-dialog-right{
    box-sizing: border-box;
    width: 420px;
    height: 400px;
    overflow: auto;
    padding:0 10px;
    display: grid;
    grid-template-columns: 50% 50%;
}
.group-dialog-account{
    padding: 10px;
}
.group-dialog-account.selected{
    background: #fff;
    box-shadow: 0 5px 4px -4px #999;
}
.group-dialog .account-item-friend{
    margin-left: 0
}
.group-dialog-group{
    width: 160px;
    margin-left: 5px;
}
.group-dialog-group-item{
    align-items: center;
    padding: 5px;
}

.replies{
    padding: 10px;
    padding: 10px;
    height: 100%;
    overflow: auto;
}
.quick-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
    box-shadow: 0px 1px 1px 1px #ddd;
    transition:transform 200ms;
    padding-right: 10px;
}
</style>
